package com.cn.onetrip.rorate3d;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.cn.onetrip.activity.R;
import com.cn.onetrip.untility.ImageUtils;
import com.cn.onetrip.untility.MD5;
import com.cn.onetrip.untility.SyncImageLoader;
import com.cn.onetrip.view.ScaleImageView;

public class ImageAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	int mGalleryItemBackground;
	private static Context mContext;
	private Handler mHandler;
	private Integer[] mImageIds;
	private ImageView[] mImages;
	private String[] mTexts, imageUrls;
	private SyncImageLoader syncImageLoader;
	public static HashMap<String, Bitmap> imagesCache = new HashMap<String, Bitmap>();

	public ImageAdapter(Context c, Handler handler, String[] ImageUrl,
			String[] text) {
		mInflater = LayoutInflater.from(c);
		syncImageLoader = new SyncImageLoader(c);
		this.mContext = c;
		this.mHandler = handler;
		this.imageUrls = ImageUrl;
		this.mTexts = text;

	}

	public void threadQuit() {
		syncImageLoader.threadQuit();
	}

	public boolean createReflectedImages() {
		int index = 0;
		for (int imageId : mImageIds) {
			Bitmap originalImage = BitmapFactory.decodeResource(
					mContext.getResources(), imageId);
			ImageView imageView = new ImageView(mContext);
			BitmapDrawable drawable = new BitmapDrawable(originalImage);
			drawable.setAntiAlias(true);
			imageView.setBackgroundDrawable(drawable);
			imageView.setLayoutParams(new GalleryFlow.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			imageView.setScaleType(ScaleType.FIT_CENTER);

			mImages[index++] = imageView;
		}
		return true;
	}

	@SuppressWarnings("unused")
	private Resources getResources() {
		// TODO Auto-generated method stub
		return null;
	}

	public int getCount() {
		return imageUrls.length;
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = mInflater.inflate(R.layout.adapter, null);
		convertView.setTag(position);
		ImageView iv = (ImageView) convertView.findViewById(R.id.galleryImage);
		TextView itemTitle = (TextView) convertView
				.findViewById(R.id.galleryTextAddress);
		iv.setImageBitmap(imagesCache.get(imageUrls[position]));
		itemTitle.setText(mTexts[position]);

		Bitmap bmp = imagesCache.get(imageUrls[position]);
		// ScaleImageView siv = (ScaleImageView) convertView
		// .findViewById(R.id.galleryScaleImage);

		// ScaleImageView view = new ScaleImageView(mContext, bmp.getWidth(),
		// bmp.getHeight());
		// siv.setLayoutParams(new Gallery.LayoutParams(
		// LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		// siv.setImageBitmap(bmp);

		return convertView;
	}

	public ScaleImageView getMyImageView(int position, int sampleSize) {
		Bitmap bmp = null;
		try {
			bmp = imagesCache.get(imageUrls[position]);
		} catch (OutOfMemoryError e) {
			try {
				bmp = BitmapFactory.decodeResource(mContext.getResources(),
						R.drawable.rc_item_bg);
			} catch (OutOfMemoryError err2) {
				err2.printStackTrace();
			}
		}
		if (bmp == null) {
			try {
				bmp = BitmapFactory.decodeResource(mContext.getResources(),
						R.drawable.rc_item_bg);
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}

		}
		// ScaleImageView view = new ScaleImageView(mContext, bmp.getWidth(),
		// bmp.getHeight());
		// view.setLayoutParams(new Gallery.LayoutParams(
		// LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		// view.setImageBitmap(bmp);
		return null;
	}

	public float getScale(boolean focused, int offset) {
		return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
	}

	public static Bitmap loadImageFromUrl(String url) throws IOException {
		if (url == null || url.length() == 0)
			return null;
		Bitmap bitmap = null;
		if (imagesCache.containsKey(url)) {
			bitmap = imagesCache.get(url);
			if (bitmap != null) {
				return bitmap;
			}
		}
		File file = new File(url);
		if (file.exists()) {
			try {
				bitmap = ImageUtils.getBitmap(file, 1);
			} catch (OutOfMemoryError e) {
				return null;
			}
			imagesCache.put(url, bitmap);
			return bitmap;
		} else {
			File f = new File(Environment.getExternalStorageDirectory() + "/"
					+ MD5.getMD5(url));
			if (f.exists()) {
				FileInputStream fis = new FileInputStream(f);
				try {
					bitmap = BitmapFactory.decodeStream(fis);
					imagesCache.put(url, bitmap);
					fis.close();
					System.gc();
					return bitmap;
				} catch (OutOfMemoryError err) {
					Log.e("OutOfMemoryError", "OutOfMemoryError");
					fis.close();
					System.gc();
					Bitmap b = null;
					try {
						b = BitmapFactory.decodeResource(
								mContext.getResources(), R.drawable.rc_item_bg);
						return b;
					} catch (OutOfMemoryError err2) {
						return null;
					}
				}
			} else {
				URL m = new URL(url);
				InputStream i = (InputStream) m.getContent();
				DataInputStream in = new DataInputStream(i);
				FileOutputStream out = new FileOutputStream(f);

				byte[] buffer = new byte[1024];
				int byteread = 0;
				while ((byteread = in.read(buffer)) != -1) {
					out.write(buffer, 0, byteread);
				}
				in.close();
				out.close();
				i.close();
				System.gc();
				// Drawable d = Drawable.createFromStream(i, "src");
				return loadImageFromUrl(url);
			}
		}
	}
}
